//
//  PlaneDebugVisualization.m
//  HKOCRuler
//
//  Created by lbxia on 2018/11/23.
//  Copyright © 2018年 lbx. All rights reserved.
//

#import "PlaneDebugVisualization.h"
#import "Utilities.h"

@implementation PlaneDebugVisualization

- (instancetype)initWithAnchor:(ARPlaneAnchor*)anchor
{
    if (self = [super init]) {
        
        self.planeAnchor = anchor;

        UIImage *grid = [UIImage imageNamed:@"art.scnassets/plane_grid.png"];
        self.planeGeometry = [Utilities createPlaneWithSize:CGSizeMake(anchor.extent.x, anchor.extent.z) contents:grid];
        
        self.planeNode = [SCNNode nodeWithGeometry:self.planeGeometry];
        
        self.planeNode.transform =SCNMatrix4MakeRotation(-M_PI/2.0, 1, 0, 0);
        
        
        
    }
    
    return self;
}

- (void)updateWithAnchor:(ARPlaneAnchor*)anchor
{
    self.planeAnchor = anchor;
    self.planeGeometry.width = anchor.extent.x;
    self.planeGeometry.height = anchor.extent.z;
    
    self.position = SCNVector3Make(anchor.center.x, -0.002, anchor.center.z);
    
    [self adjustScale];
}

- (void)adjustScale
{
    CGFloat scaledWidth = self.planeGeometry.width / 2.4;
    CGFloat scaledHeight = self.planeGeometry.height / 2.4;
    
    CGFloat offsetWidth = -0.5 * (scaledWidth - 1);
    CGFloat offsetHeight = -0.5 * (scaledHeight - 1);
    
    SCNMaterial *material = self.planeGeometry.materials.firstObject;
    SCNMatrix4 transform  = SCNMatrix4MakeScale(scaledWidth, scaledHeight, 1);
    transform =  SCNMatrix4Translate(transform, offsetWidth, offsetHeight, 0);
    material.diffuse.contentsTransform = transform;
}

@end
